package com.example.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.common.R;
import com.example.his.api.constant.SystemEnum;
import com.example.his.api.db.pojo.UserEntity;
import com.example.his.api.mis.controller.form.*;
import com.example.his.api.mis.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huixh
 */
@RestController
@RequestMapping("/mis/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody @Valid LoginForm loginForm){
        Map<String, Object> map = BeanUtil.beanToMap(loginForm);
        Integer userId = userService.login(map);
        if (userId != null) {
            // 同端互斥
            StpUtil.logout(userId, SystemEnum.WEB.getType());
            StpUtil.login(userId, SystemEnum.WEB.getType());
            // 生成令牌 （web端）
            String webToken = StpUtil.getTokenValueByLoginId(userId, SystemEnum.WEB.getType());
            // 获取用户权限
            List<String> permissionList = StpUtil.getPermissionList();
            // 返回数据
            return R.ok().put("result",true).put("token",webToken).put("permissionList",permissionList);
        }
        return R.resultFail();
    }

    @GetMapping("/logout")
    public R logout(){
        int userId = StpUtil.getLoginIdAsInt();
        StpUtil.logout(userId, SystemEnum.WEB.getType());
        return R.resultOk();
    }

    @PostMapping("/updatePassword")
    @SaCheckLogin
    public R updatePassword(@RequestBody @Valid UpdatePasswordFrom updatePasswordFrom){
        Map<String, Object> map = BeanUtil.beanToMap(updatePasswordFrom);
        int userId = StpUtil.getLoginIdAsInt();
        map.put("userId",userId);
        int result = userService.updatePassword(map);
        if (result > 0) {
            return R.resultOk();
        }
        return R.resultFail();
    }

    @PostMapping("/searchByPage")
    @SaCheckPermission(value = {"ROOT","USER:SELECT"},mode = SaMode.OR)
    public R searchByPage(@RequestBody @Valid SearchUserPageForm searchUserPageForm){
        Integer page = searchUserPageForm.getPage();
        Integer length = searchUserPageForm.getLength();
        int start = (page - 1) * length;
        Map<String, Object> map = BeanUtil.beanToMap(searchUserPageForm);
        map.put("start",start);
        PageUtils pageUtils = userService.searchByPage(map);
        return R.resultOk().put("page", pageUtils);
    }
    @PostMapping("/insert")
    @SaCheckPermission(value = {"ROOT","USER:INSERT"},mode = SaMode.OR)
    public R insert(@RequestBody @Valid InsertUserForm insertUserForm){
        UserEntity user = BeanUtil.toBean(insertUserForm, UserEntity.class);
        user.setStatus(1);
        user.setRole(JSONUtil.parseArray(insertUserForm.getRole()).toString());
        int result = userService.insert(user);
        return R.resultOk().put("rows",result);
    }

    @PostMapping("/searchById")
    @SaCheckPermission(value = {"ROOT","USER:SELECT"},mode = SaMode.OR)
    public R searchById(@RequestBody @Valid SearchUserByIdForm form){
        HashMap<?, ?> user = userService.searchById(form.getUserId());
        return R.resultOk().put("result",user);
    }

    @PostMapping("/update")
    @SaCheckPermission(value = {"ROOT","USER:UPDATE"},mode = SaMode.OR)
    public R update(@RequestBody @Valid UpdateUserForm form){
        Map<String, Object> map = BeanUtil.beanToMap(form);
        map.put("role",JSONUtil.parseArray(form.getRole()).toString());
        int result = userService.update(map);
        if (result == 1) {
            StpUtil.logout(form.getUserId());
        }
        return R.resultOk().put("rows",result);
    }

    @PostMapping("/delete")
    public R delete(@RequestBody @Valid DeleteUserByIdsForm form){
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        if(ArrayUtil.contains(form.getIds(),loginIdAsInt)) {
            return R.error("不能删除自己");
        }
        if (userService.deleteByIds(form.getIds()) > 0) {
            for (Integer id : form.getIds()) {
                StpUtil.logout(id);
            }
            return R.resultOk();
        }
        return R.resultFail();
    }
}
